package cn.edu.whu.forecast.service.impl;

import cn.edu.whu.forecast.common.PageBean;
import cn.edu.whu.forecast.dto.UserDetailsDto;
import cn.edu.whu.forecast.entity.mysql.Message;
import cn.edu.whu.forecast.mapper.mysql.MessageMapper;
import cn.edu.whu.forecast.service.LogMessageService;
import cn.edu.whu.forecast.vo.request.LogModifyVo;
import cn.edu.whu.forecast.vo.response.MessageVo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class LogMessageServiceImpl implements LogMessageService {

    @Resource
    private MessageMapper messageMapper;

    @Override
    public PageBean<MessageVo> GetLogs(LocalDateTime startTime, LocalDateTime endTime, String type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Message> logs = messageMapper.getLogs(startTime, endTime, type);
        List<MessageVo> vos = new ArrayList<>();
        logs.forEach(log->{
            MessageVo messageVo = new MessageVo();
            BeanUtils.copyProperties(log,messageVo);
            vos.add(messageVo);
        });

        PageBean<MessageVo> pageBean = new PageBean<>(vos);
        pageBean.setList(vos);

        return pageBean;
    }

    @Override
    public int modifyStatus(LogModifyVo logModifyVo) {
        return messageMapper.updateStatus(logModifyVo.getLogId(), logModifyVo.getStatus());
    }

    @Override
    public void insertLog(Boolean isAuto, Integer type, String content) {
        String userName = null;
        // 获得用户名
        if(isAuto){
            userName = "系统自动执行";
        }
        else{

            UserDetailsDto user = (UserDetailsDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userName = user.getName();;
        }
        Message message = new Message();
        message.setIsChecked(2);
        message.setContent(content);
        message.setTime(LocalDateTime.now());
        message.setType(type);
        message.setUsername(userName);
        messageMapper.insertSelective(message);
    }

    @Override
    public void insertLog(Boolean isAuto, Integer type, String content, String username) {
        Message message = new Message();
        message.setIsChecked(2);
        message.setContent(content);
        message.setTime(LocalDateTime.now());
        message.setType(type);
        message.setUsername(username);
        messageMapper.insertSelective(message);
    }

}
